package excel;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.poifs.crypt.Decryptor;
import org.apache.poi.poifs.crypt.EncryptionInfo;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class XLSXDecryptor {
    public static void decryptXLSX(String sourceFile, String destinationFile, String password) {
        try {
            FileInputStream fis = new FileInputStream(sourceFile);
            FileOutputStream fos = new FileOutputStream(destinationFile);

            POIFSFileSystem pfs = new POIFSFileSystem(fis);
            EncryptionInfo info = new EncryptionInfo(pfs);
            Decryptor decryptor = Decryptor.getInstance(info);

            boolean res = decryptor.verifyPassword(password);
            while (!res) {

            }
            HSSFWorkbook workbook = new HSSFWorkbook(decryptor.getDataStream(pfs));

            workbook.write(fos);

            fos.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String sourceFile = "demo/src/main/java/excel/【202406】海语海数请批.xlsx";
        String destinationFile = "demo/src/main/java/excel/【202406】海语海数请批1.xlsx";
        String password = "password";

        decryptXLSX(sourceFile, destinationFile, password);
    }
}